﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Alchemy;
using Alchemy.Classes;

namespace RiftServerGUI
{
    unsafe class RiftServer
    {
        private WebSocketServer server;
        private UserContext context;

        [DllImport(@"RiftWrapper.dll")]
        static extern int OVR_Init();

        [DllImport(@"RiftWrapper.dll", CallingConvention = CallingConvention.Cdecl)]
        static extern int OVR_Peek(float* w, float* x, float* y, float* z);

        [DllImport(@"RiftWrapper.dll", CallingConvention = CallingConvention.Cdecl)]
        static extern int OVR_PeekYPL(float* yaw, float* pitch, float* roll);

        private bool _running = false;

        public RiftServer()
        {
            OVR_Init();
            server = new WebSocketServer(1981, IPAddress.Any)
            {
                OnSend = OnSend,
                OnConnected = OnConnect,
                OnDisconnect = OnDisconnect
            };
            server.Start();
        }     

        public void Start()
        {
            _running = true;
            Thread thread = new Thread(new ThreadStart(Client));
            thread.Start();
        }

        public void Stop()
        {
            _running = false;
            server.Stop();
        }

        unsafe void Client()
        {
            float y, p, r;
            CultureInfo culture = new System.Globalization.CultureInfo("en-US");

            while (_running)
            {
                OVR_PeekYPL(&y, &p, &r);
                string ss = string.Format(culture, "{0},{1},{2}", y, p, r);
                this.context.Send(ss);
                System.Threading.Thread.Sleep(10);
            }
        }

        public void OnConnect(UserContext context)
        {
            this.context = context;
            Console.WriteLine("Client Connection From : " + context.ClientAddress);
            //Client(context);
        }

        public void OnSend(UserContext context)
        {
            Console.WriteLine("Data Send To : " + context.ClientAddress);
        }

        public void OnDisconnect(UserContext context)
        {
            Console.WriteLine("Client Disconnected : " + context.ClientAddress);
        }
    }
}
